#!/bin/bash
# RabbitMQ 服务管理脚本

set -e

COMPOSE_FILE="docker-compose.yml"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 显示帮助信息
show_help() {
    echo "用法: $0 [start|stop|restart|status|enable-plugin|disable-plugin]"
    echo ""
    echo "命令:"
    echo "  start          启动 RabbitMQ 服务"
    echo "  stop           停止 RabbitMQ 服务"
    echo "  restart        重启 RabbitMQ 服务"
    echo "  status         查看 RabbitMQ 服务状态"
    echo "  enable-plugin  启用延迟消息插件"
    echo "  disable-plugin 禁用延迟消息插件"
    echo ""
    echo "示例:"
    echo "  $0 start"
    echo "  $0 enable-plugin"
}

# 检查 docker-compose.yml 文件
check_compose_file() {
    if [ ! -f "$COMPOSE_FILE" ]; then
        echo -e "${RED}❌ 未找到 $COMPOSE_FILE 文件，请在 docker-compose.yml 所在目录运行${NC}"
        exit 1
    fi
}

# 启动服务
start_services() {
    echo -e "${YELLOW}🚀 启动 RabbitMQ...${NC}"
    docker compose up -d rabbitmq
    
    echo -e "${GREEN}✅ RabbitMQ 已启动完成${NC}"
    docker ps --filter "name=rabbitmq3"
}

# 停止服务
stop_services() {
    echo -e "${YELLOW}🛑 停止 RabbitMQ...${NC}"
    docker compose stop rabbitmq
    
    echo -e "${GREEN}✅ RabbitMQ 已停止${NC}"
    docker ps --filter "name=rabbitmq3"
}

# 重启服务
restart_services() {
    echo -e "${YELLOW}🔄 重启 RabbitMQ...${NC}"
    docker compose restart rabbitmq
    
    echo -e "${GREEN}✅ RabbitMQ 已重启${NC}"
    docker ps --filter "name=rabbitmq3"
}

# 启用延迟消息插件
enable_plugin() {
    echo -e "${YELLOW}🔧 启用延迟消息插件...${NC}"
    docker compose exec rabbitmq rabbitmq-plugins enable --offline rabbitmq_delayed_message_exchange
    
    echo -e "${GREEN}✅ 延迟消息插件已启用${NC}"
}

# 禁用延迟消息插件
disable_plugin() {
    echo -e "${YELLOW}🔧 禁用延迟消息插件...${NC}"
    docker compose exec rabbitmq rabbitmq-plugins disable --offline rabbitmq_delayed_message_exchange
    
    echo -e "${GREEN}✅ 延迟消息插件已禁用${NC}"
}

# 查看服务状态
status_services() {
    echo -e "${YELLOW}📋 RabbitMQ 服务状态:${NC}"
    docker ps --filter "name=rabbitmq3"
}

# 主程序
main() {
    if [[ $# -eq 0 ]]; then
        show_help
        exit 1
    fi
    
    check_compose_file
    
    case "$1" in
        start)
            start_services
            ;;
        stop)
            stop_services
            ;;
        restart)
            restart_services
            ;;
        status)
            status_services
            ;;
        enable-plugin)
            enable_plugin
            ;;
        disable-plugin)
            disable_plugin
            ;;
        -h|--help)
            show_help
            ;;
        *)
            echo -e "${RED}❌ 未知命令: $1${NC}"
            show_help
            exit 1
            ;;
    esac
}

# 执行主程序
main "$@"